package com.gears_software.mapdemo;

import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.gears_software.mapdemo.map.LocationTask;
import com.gears_software.mapdemo.map.OnLocationGetListener;
import com.gears_software.mapdemo.map.RegeocodeTask;
import com.gears_software.mapdemo.model.PositionEntity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

/**
 * Created by lileltp on 2017/9/24.
 */

public class Demo1Activity extends AppCompatActivity implements AMap.OnMapLoadedListener, LocationSource, AMap.OnCameraChangeListener, OnLocationGetListener {
    MapView mMapView = null;
    AMap aMap;
    TextView txt_show;
    private LocationTask mLocationTask;
    private LatLng mStartPosition;//起点
    private boolean mIsFirst = true;
    private RegeocodeTask mRegeocodeTask;
    private LocationSource.OnLocationChangedListener mListener = null;//定位监听器
    AMapLocation aMapLocation;
    Context context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_demo1);
        mLocationTask = LocationTask.getInstance(this);
        mLocationTask.setOnLocationGetListener(this);
        mRegeocodeTask = new RegeocodeTask(this);
//        RouteTask.getInstance(this).addRouteCalculateListener(this);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        txt_show = (TextView) findViewById(R.id.txt_show);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        //获取定位权限
        AndPermission.with(this)
                .requestCode(200)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .callback(listener)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(context, rationale).
                                show();
                    }
                })
                .start();

    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            if (requestCode == 200) {
//                TastyToast.makeText(context, "获取定位权限成功", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                initMap();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            if (requestCode == 200) {
                Log.d("demo", "获取定位权限失败");
            }
        }
    };

    private void initMap(){
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));

        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        //地图上不显示放大缩小按钮
        settings.setZoomControlsEnabled(false);
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(true);

        //设置定位监听
        aMap.setLocationSource(this);
        //是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        //定位的小图标 默认是蓝点 其实就是一张图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps1));
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
        aMap.setMyLocationStyle(myLocationStyle);

        aMap.setOnMapLoadedListener(this);
        aMap.setOnCameraChangeListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        mLocationTask.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onMapLoaded() {
        mLocationTask.startSingleLocate();
    }

    @Override
    public void onLocationGet(PositionEntity entity, AMapLocation aMapLocation) {
        String address = entity.getAddress().replace(entity.getProvince(), "").replace(entity.getCity(), "").replace(entity.getDistrict(), "");
        txt_show.setText(address);
//        RouteTask.getInstance(getContext()).setStartPoint(entity);
        mStartPosition = new LatLng(entity.getLatitue(), entity.getLongitude());
        if (mIsFirst) {
            this.aMapLocation = aMapLocation;
//            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(mStartPosition, 17);
//            aMap.animateCamera(cameraUpdate);
            //设置缩放级别
            aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
            //将地图移动到定位点
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(mStartPosition));
            mListener.onLocationChanged(aMapLocation);
            mIsFirst = false;
        }
    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {
        String address = entity.getAddress().replace(entity.getProvince(), "").replace(entity.getCity(), "").replace(entity.getDistrict(), "");
        txt_show.setText(address);
        entity.setLatitue(mStartPosition.latitude);
        entity.setLongitude(mStartPosition.longitude);
//        startEntity = entity;
//        RouteTask.getInstance(getContext()).setStartPoint(entity);
//        RouteTask.getInstance(getContext()).search();
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        mStartPosition = cameraPosition.target;
        mRegeocodeTask.setOnLocationGetListener(this);
        mRegeocodeTask.search(mStartPosition.latitude, mStartPosition.longitude);
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;

    }

    @Override
    public void deactivate() {
        mListener = null;
    }
}
